package com.mbv5.xml;

import java.util.Properties;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;

import org.apache.ibatis.builder.BuilderException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Created by qiao on 2017/1/7.
 */
public class XPathParser {
    private Document document;
    private XPath xPath;
    private Properties variables;

    public XPathParser(Document document, XPath xPath) {
        this.document = document;
        this.xPath = xPath;
    }

    public XNode evalNode(String expression) {
        return evalNode(document, expression);
    }

    public XNode evalNode(Object object, String expression) {
        Node node = evaluate(expression, object, XPathConstants.NODE);
        if (null == node) {
            return null;
        }
        return new XNode(this, node, variables);
    }

    private Node evaluate(String expression, Object root, QName qName) {
        try {
            return (Node) xPath.evaluate(expression, root, qName);
        } catch (Exception e) {
            throw new BuilderException("Error evaluating XPath.  Cause: " + e, e);
        }
    }
}
